package com.ruoyi.quartz.controller;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.job.TaskException;
import com.ruoyi.quartz.domain.SysJob;
import com.ruoyi.quartz.service.ISysJobService;
import com.ruoyi.quartz.util.ScheduleUtils;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/remote/monitor/job")
public class SysJobRemoteController {
    @Autowired
    private ISysJobService jobService;
    @Resource(name = "schedulerFactoryBean")
    private Scheduler remoteScheduler;
    @Resource(name = "localScheduler")
    private Scheduler localScheduler;
    public Map<String,Scheduler> schedulerMap=new HashMap<>();

    /**
     * 项目启动时，初始化定时器 主要是防止手动修改数据库导致未同步到定时任务处理（注：不能手动修改数据库ID和任务组名，否则会导致脏数据）
     */
    @PostConstruct
    public void init() throws SchedulerException, TaskException
    {
        schedulerMap.put("remote",remoteScheduler);
        schedulerMap.put("local",localScheduler);
    }
    private Scheduler determinSche(SysJob job){
        return schedulerMap.get(job.getEngine());
    }

    @ModelAttribute
    public void modelAttr(HttpServletRequest request){
        log.info("收到请求"+request.getRequestURI());
    }

    @RequestMapping("/remote/call/{method}/{jobId}/{jobGroup}")
    public Object remoteCall(@PathVariable("method") String method,@PathVariable("jobId") String jobId,@PathVariable("jobGroup") String jobGroup){
        if ("resumeJob".equals(method)){
            SysJob byId = jobService.selectJobById(Long.parseLong(jobId));
            if (byId!=null){
                byId.setStatus("0");
                jobService.updateById(byId);
            }
        }else if ("pauseJob".equals(method)){
            SysJob byId = jobService.selectJobById(Long.parseLong(jobId));
            if (byId!=null){
                byId.setStatus("1");
                jobService.updateById(byId);
            }
        }
        jobService.call(method,jobId,jobGroup);
        return AjaxResult.success();
    }

    @RequestMapping("/createScheduleJob/{jobId}")
    public void createScheduleJob(@PathVariable("jobId") Integer jobId)throws Exception{
        SysJob job=jobService.getById(jobId);
        ScheduleUtils.createScheduleJob(determinSche(job), job);
    }
    @RequestMapping("/pauseJob/{jobId}/{jobGroup}")
    public void pauseJob(@PathVariable("jobId") Long jobId,@PathVariable("jobGroup") String jobGroup)throws Exception{
        SysJob job=jobService.getById(jobId);
        determinSche(job).pauseJob(ScheduleUtils.getJobKey(jobId, jobGroup));
    }

    @RequestMapping("/resumeJob/{jobId}/{jobGroup}")
    public void resumeJob(@PathVariable("jobId") Long jobId,@PathVariable("jobGroup") String jobGroup)throws Exception{
        SysJob job=jobService.getById(jobId);
        determinSche(job).resumeJob(ScheduleUtils.getJobKey(jobId, jobGroup));
    }

    @RequestMapping("/deleteJob/{jobId}/{jobGroup}")
    public void deleteJob(@PathVariable("jobId") Long jobId,@PathVariable("jobGroup") String jobGroup)throws Exception{
        SysJob job=jobService.getById(jobId);
        determinSche(job).deleteJob(ScheduleUtils.getJobKey(jobId, jobGroup));
    }

    @RequestMapping("/updateSchedulerJob/{jobId}/{jobGroup}")
    public void updateSchedulerJob(@PathVariable("jobId") Long jobId,@PathVariable("jobGroup") String jobGroup)throws Exception{
        SysJob job=jobService.getById(jobId);
        JobKey jobKey = ScheduleUtils.getJobKey(jobId, jobGroup);
        Scheduler scheduler = determinSche(job);
        if (scheduler.checkExists(jobKey))
        {
            // 防止创建时存在数据问题 先移除，然后在执行创建操作
            scheduler.deleteJob(jobKey);
        }
        ScheduleUtils.createScheduleJob(scheduler, job);
    }
}
